import { Injectable, EventEmitter } from '@angular/core';
import { CHART_TAB_LIST, CHART_TAB } from "stock";

export const TOP_BAR_TYPE_CHART = 0;
export const TOP_BAR_TYPE_FUND = 1;
export const TOP_BAR_TYPE_TICK = 2;
export const ACTION_SET_BAR_TYPE = 0;
export const ACTION_ITEM_CLICK = 1;
export const ACTION_GO_NEXT = 2;
export const ACTION_GO_PRE = 3;

const findTab = (tabList: typeof CHART_TAB_LIST) =>
  (activeTab: CHART_TAB) =>
    (indexToAdd: number) => {
      let parents = tabList
        .filter(tab =>
          tab.canControlFromOuter && tab.children)
        .map(tab => tab.children)
        .filter(list => list.some(tab => tab.key === activeTab.key))
        .reduce((pre, next) => next, [])
      if (!parents.length) return activeTab;
      let index = parents.findIndex(tab => tab.key === activeTab.key);
      if (index === -1) return activeTab;
      return parents[Math.min(Math.max(0, index + indexToAdd), parents.length - 1)]
    };

@Injectable()
export class StockTopBarService {
  source = new EventEmitter;
  clickSource = new EventEmitter;
  output = new EventEmitter;
  method = "";
  currentList: typeof CHART_TAB_LIST;
  currentActive: CHART_TAB;
  currentType;
  constructor() {
    // this.source.subscribe(some => console.debug("%c TopBarSerivce: Source Triggle:: ", 'color:#f00', some));
    this.source.subscribe(action => {
      switch (action["type"]) {
        case ACTION_SET_BAR_TYPE:
          this.currentType = action["tabType"];
          return this.currentList = action["payload"];
        case ACTION_ITEM_CLICK:
          this.currentActive = action["payload"];
          return this.output.next(action["payload"]);
        case ACTION_GO_NEXT:
          return this.tabGo(1);
        case ACTION_GO_PRE:
          return this.tabGo(-1);
        default: return;
      }
    });
  }

  tabGo(indexToAdd: number) {
    this.clickSource.next(findTab(this.currentList)(this.currentActive)(indexToAdd));
  }

}